import numpy as np
import pandas as pd
from keras.models import load_model
import pickle

# 1.输入文件夹
testfile_path = r"F:\dataset\BQW_min\Group\A1_new\202403.csv" #####根据情况调整
# 2.模型权重文件地址
model_path = r"F:\time_series_my_algorithm\60min\发送版2\model\GeneratorWindingTemperature2_Model.h5"  ###根据情况修改
# 3.数据归一化地址
scaler_path = r"F:\time_series_my_algorithm\60min\发送版2\scale\GeneratorWindingTemperature2_scaler.pkl" ####根据情况修改
# 4.目标值和特征值文件地址
feature_data = pd.read_csv(r"F:\time_series_my_algorithm\60min\发送版2\feature.csv")  ####根据情况调整
target_name = feature_data.iloc[1, 0]
need_names = feature_data.iloc[1, 1:3].tolist()


time_name = 'rectime'
N_past_value = 60
Pre_size = 60
Lstm_input_size = len(need_names) + 1
# 加载测试数据
df_test = pd.read_csv(testfile_path)           ##### 输入数据格式为csv，根据实际情况需进行修改
# 数据预处理函数
def prepare_data(data, scaler):
    # 提取目标列和特征列
    target = data[[target_name]].values
    features = data[need_names].values
    # 合并并缩放
    full_data = np.concatenate([target, features], axis=1)
    scaled_data = scaler.transform(full_data)
    return scaled_data[:, 0], scaled_data[:, 1:], target  # 返回(y, X,原始y)


# 加载scaler
with open(scaler_path, 'rb') as f:
    scaler = pickle.load(f)

# 加载模型
model = load_model(model_path)

# 随机选择预测起点,该部分因为输入为csv文件，且是为了测试而选择的。现场不需要该处代码，实时调用scada数据即可
max_start = len(df_test) - N_past_value - Pre_size
start_idx = np.random.randint(0, max_start)
print(f"\n随机选择起始索引：{start_idx}")

# 准备输入数据
raw_segment = df_test.iloc[start_idx:start_idx + N_past_value + Pre_size]
y_scaled, X_scaled, y_true = prepare_data(raw_segment, scaler)

# 构建输入序列 (符合模型预期的三维结构)
sequence = np.concatenate([
    y_scaled[:N_past_value].reshape(-1, 1),
    X_scaled[:N_past_value]
], axis=1)[np.newaxis, ...]  # 添加batch维度

# 进行预测
#pred_scaled = model.predict(sequence)[0, :, 0]  # 获取预测序列
pred_scaled = model.predict(sequence)[0, :]
# 逆标准化预测结果
pred_full = np.concatenate([
    pred_scaled.reshape(-1, 1),
    X_scaled[N_past_value:N_past_value + Pre_size]
], axis=1)
# 输出预测结果
pred = scaler.inverse_transform(pred_full)[:, 0]
print(pred)
# 输出真实值
true_values = y_true[N_past_value:N_past_value + Pre_size].flatten()
print(true_values)
